<template>
	<div class="bg-gray-100 h-screen">
		<div class="mx-2 mb-2 p-2 shadow-sm h-[12vh]" v-if="showChoose">
			<div
				@click="chooseStatus = 'start'"
				:class="[
					{ 'border-gray-300': chooseStatus === 'end' },
					{
						'border-indigo-600': chooseStatus === 'start',
					},
					'border-2 p-1 mb-1 rounded',
				]"
			>
				{{ userPosition.positionId !== "" ? userPosition.positionName : "请选择起始点" }}
			</div>
			<div
				@click="chooseStatus = 'end'"
				:class="[
					{ 'border-gray-300': chooseStatus === 'start' },
					{
						'border-indigo-600': chooseStatus === 'end',
					},
					'border-2 p-1 mb-1 rounded',
				]"
			>
				{{ userPosition.toPositionId !== "" ? userPosition.toPositionName : "请选择终点" }}
			</div>
		</div>
		<div id="container" :style="{ height: showChoose ? '55vh' : '75vh' }"></div>
		<div class="flex justify-around my-2">
			<van-button type="primary" @click="showQr">出示乘车二维码</van-button>
			<van-button type="primary" @click="bookingCar">预约上车</van-button>
		</div>

		<div>
			<van-floating-panel :anchors="anchors">
				<van-cell-group>
					<div>
						<van-search v-model="search" placeholder="请输入搜索关键词" />
					</div>
					<div v-for="(item, index) in positionList" :key="index" class="mt-2 p-2 border-b-2" @click="choose(item)">
						{{ item.name }}
					</div>
				</van-cell-group>
			</van-floating-panel>
		</div>

		<van-dialog v-model:show="showQrActive" title="乘车二维码" :closeOnClickOverlay="true">
			<img :src="qrCode" alt="" />
		</van-dialog>
	</div>
</template>
<script setup>
import AMapLoader from "@amap/amap-jsapi-loader";

import { getCarPositionList } from "@/api/car.js";
import { computed, onMounted, onUnmounted, reactive, ref } from "vue";
import { getPositionList } from "@/api/position.js";
import { closeToast, showConfirmDialog, showLoadingToast, showToast } from "vant";
import { createQrCode, userAddOrder } from "@/api/order.js";
import { useRouter } from "vue-router";
// window._AMapSecurityConfig = {
// 	securityJsCode: "34f6a037c26acc06c1df5d7f15efd0a1",
// };

const anchors = ref([window.innerHeight * 0.2, window.innerWidth]);
// 地图实例
let map = null;

// 当前选择的站点
let chooseMarker = null;

// 车辆位置
const carMap = ref({});

// 原始站点列表
const originalPositionList = ref([]);

//展示的站点列表
const positionList = computed(() => {
	if (!search.value) return originalPositionList.value;
	return originalPositionList.value.filter((item) => item.name.includes(search.value));
});

// 搜索关键词
const search = ref("");
// 是否展示二维码
const showQrActive = ref(false);
const qrCode = ref("");

const showChoose = ref(true);
const chooseStatus = ref("start");

const userPosition = reactive({
	positionId: "",
	toPositionId: "",
	positionName: "",
	toPositionName: "",
});

const router = useRouter();

onMounted(() => {
	AMapLoader.load({
		key: "b8443bf0d6c803f350308eaf819eaebf", // 申请好的Web端开发者Key，首次调用 load 时必填
		version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
		plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
	})
		.then((AMap) => {
			map = new AMap.Map("container", {
				// 设置地图容器id
				viewMode: "2D", // 是否为3D地图模式
				zoom: 17, // 初始化地图级别
				center: [104.598563, 31.453966], // 初始化地图中心点位置
			});
			refreshCarPosition();
			// // 创建一个 Marker 实例：
			// const marker = new AMap.Marker({
			// 	isCustom: true, // 使用自定义点标记
			// 	position: [104.598563,31.453966], // 设置标注点坐标
			// 	content: '<img src="/car.png" class="car1" style="width: 6vw;height: 6vh" />',
			// 	map: map, // 设置标注点所在地图实例
			// });
		})
		.catch((e) => {
			console.log(e);
		});

	loadPositionList();
});
const loadPositionList = async () => {
	const positionListResult = await getPositionList();
	if (positionListResult) {
		originalPositionList.value = positionListResult.data;
	}
};
/**
 * 2s 刷新一次车辆位置
 */
let refreshCarPositionTimer = null;
const refreshCarPosition = () => {
	refreshCarPositionTimer = setInterval(async () => {
		const carPositionListResult = await getCarPositionList();
		if (carPositionListResult) {
			for (let i = 0; i < carPositionListResult.data.length; i++) {
				let data = carPositionListResult.data[i];
				if (carMap.value[data.carId]) {
					carMap.value[data.carId].setPosition(data.position.split(","));
				} else {
					carMap.value[data.carId] = new AMap.Marker({
						isCustom: true, // 使用自定义点标记
						position: data.position.split(","), // 设置标注点坐标
						content: '<img src="/car.png" style="width: 6vw;height: 6vh" />',
						map: map, // 设置标注点所在地图实例
					});
				}
			}
		}
	}, 500);
};

/**
 * 选择站点
 * @param item
 */
const choose = (item) => {
	if (chooseStatus.value === "start") {
		userPosition.positionId = item.id;
		userPosition.positionName = item.name;
	} else {
		userPosition.toPositionId = item.id;
		userPosition.toPositionName = item.name;
	}

	const position = item.position.split(",");
	map.setCenter(position);
	if (!chooseMarker) {
		chooseMarker = new AMap.Marker({
			position: position, // 设置标注点坐标
			icon: new AMap.Icon({
				image: "/poi-marker-default.png",
				size: new AMap.Size(24, 30),
				imageSize: new AMap.Size(24, 30),
			}),
			map: map, // 设置标注点所在地图实例
		});
		console.log(chooseMarker);
	} else {
		chooseMarker.setPosition(position);
	}
};

/**
 * 出示乘车二维码
 */
const showQr = async () => {
	showLoadingToast({
		message: "加载中...",
		forbidClick: true,
	});
	const res = await createQrCode();
	if (res) {
		qrCode.value = res.data;
		showQrActive.value = true;
	}
};
/**
 * 预约上车
 */
const bookingCar = () => {
	if (userPosition.positionId === "" || userPosition.toPositionId === "") {
		showToast({
			message: "请选择起始点和终点",
		});
		return;
	}
	if (userPosition.positionId === userPosition.toPositionId) {
		showToast({
			message: "起始点和终点不能相同",
		});
		return;
	}
	showConfirmDialog({
		title: "提示",
		message: `是否确认预约上车 [${userPosition.positionName}]-[${userPosition.toPositionName}] ？`,
	})
		.then(async () => {
			showLoadingToast({
				message: "预约中...",
				forbidClick: true,
			});
			const res = await userAddOrder({
				positionId: userPosition.positionId,
				toPositionId: userPosition.toPositionId,
			});
			if (res) {
				showToast({
					message: "预约成功",
				});
				showChoose.value = false;
			}
		})
		.catch(() => {
			showToast({
				message: "取消预约",
			});
		});
};

onUnmounted(() => {
	map?.destroy();
	if (refreshCarPositionTimer) {
		clearInterval(refreshCarPositionTimer);
		refreshCarPositionTimer = null;
	}
});
</script>
<style scoped>
#container {
	width: 100vw;
	height: 75vh;
}
</style>
